package com.lli.mc.converter.openoffice;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;

public class OpenOfficeConnectionFactory extends
        BasePooledObjectFactory<OpenOfficeConnection> {
    private static final Logger log = LoggerFactory
            .getLogger(OpenOfficeConnectionFactory.class);

    private String host ;
    private int port;

    public OpenOfficeConnectionFactory(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 销毁对象 <br>
     * 如果是对象是线程，线程必须已结束，如果是socket，socket必须已close，如果是文件操作，文件数据必须已flush， 且文件正常关闭。
     */
    public void destroyObject(PooledObject<OpenOfficeConnection> pool)
        throws Exception {
        OpenOfficeConnection obj = pool.getObject();
        if (obj != null) {
            obj.disconnect();

        }

    }

    /**
     * 创建对象
     */
    @Override
    public OpenOfficeConnection create() throws Exception {
        // 1: 打开连接
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(host,
                port);
        connection.connect();
        log.info("创建openoffice连接：{}", connection);
        return connection;
    }

    @Override
    public PooledObject<OpenOfficeConnection> wrap(OpenOfficeConnection obj) {
        return new DefaultPooledObject<OpenOfficeConnection>(obj);
    }

}